import React, { useEffect, useRef, useState } from "react";
import "./Swiper.css";

// 定义导航项的类型
interface NavItem {
  nid: number;
  url: string;
  img: string;
  imgActive: string;
  title: string;
}

export default function Index() {
  const animationRef = useRef<HTMLUListElement>(null);

  // 定义一个状态控制动画的执行和暂停
  const [animationDis, setAnimationDis] = useState(false);

  // 定义一个变量，用来存储选中后的选项的 id
  const [activeKey, setActiveKey] = useState(0);

  // 定义一组导航的数据
  const [navLi] = useState<NavItem[]>([
    {
      nid: 101,
      url: "",
      img: "/public/image/交通事故智能定位分析系统_nor.png",
      imgActive: "/public/image/交通事故智能定位分析系统_hov.png",
      title: "交通事故智能定位分析系统",
    },
    {
      nid: 102,
      url: "",
      img: "/public/image/非机动车未带头盔识别系统_nor.png",
      imgActive: "/public/image/非机动车未带头盔识别系统_hov.png",
      title: "非机动车未带头盔识别系统",
    },
    {
      nid: 103,
      url: "",
      img: "/public/image/交通安全画像系统_nor.png",
      imgActive: "/public/image/交通安全画像系统_hov.png",
      title: "交通安全画像系统",
    },
    {
      nid: 104,
      url: "",
      img: "/public/image/交通态势监控系统_nor.png",
      imgActive: "/public/image/交通态势监控系统_hov.png",
      title: "交通态势监控系统",
    },
    {
      nid: 105,
      url: "",
      img: "/public/image/可视化作战平台_nor.png",
      imgActive: "/public/image/可视化作战平台_hov.png",
      title: "可视化作战平台",
    },
    {
      nid: 106,
      url: "",
      img: "/public/image/重点车辆监管系统_nor.png",
      imgActive: "/public/image/重点车辆监管系统_hov.png",
      title: "重点车辆监管系统",
    },
  ]);

  // useEffect
  useEffect(() => {
    if (animationRef.current) {
      // 当页面加载的时候，为每一个导航的轮播图片添加延迟时间
      Array.from(animationRef.current.children).forEach((item, index) => {
        item.style["animation-delay"] =
          -5 - 3.3 * index + "s," + -3.3 * index + "s," + -3.3 * index + "s";
      });
    }
  }, []);

  const onMouseEnter = (nid: number) => {
    setAnimationDis(true);
    setActiveKey(nid);
  };

  const onMouseLeave = () => {
    setAnimationDis(false);
    setActiveKey(0);
  };

  const onClick = (title: string) => {
    alert(title);
  };

  return (
    <div>
      <div className="navWrap">
        <ul ref={animationRef}>
          {navLi.map((item) => (
            <li
              key={item.nid}
              className={animationDis ? "animation_paused" : ""}
              onMouseEnter={() => onMouseEnter(item.nid)}
              onMouseLeave={onMouseLeave}
              onClick={() => onClick(item.title)}
            >
              <img
                src={activeKey === item.nid ? item.imgActive : item.img}
                alt="图片加载失败"
              />
              <span>{item.title}</span>
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
}
